﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WebApiClient;
using WebApiClient.Contexts;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using Cache.CSRedis;

namespace OrderWebApi
{
    public class WebApiClientGlobalFilter : IApiActionFilter
    {        
        private readonly IHttpContextAccessor _httpContextAccessor;
        public WebApiClientGlobalFilter(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public async Task OnBeginRequestAsync(ApiActionContext context)
        {
            var accessToken = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token");
            context.RequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        }

        public async Task OnEndRequestAsync(ApiActionContext context)
        {
            await Task.CompletedTask;
        }
    }
}
